# coding:utf-8

import time

from Setting import HTML_ROOT_DIR


class Application(object):
    """框架核心，框架路由"""
    def __init__(self, urls):
        self.urls = urls

    def __call__(self, env, start_response):
        path = env.get("PATH_INFO", "/")
        if path.startswith("/static"):
            # 访问静态文件
            file_name = path[7:]
            try:
                file = open(HTML_ROOT_DIR + file_name, "rb")
            except IOError:
                # 代表未找到路由信息，404错误
                status = "404 Not Found"
                headers = []
                start_response(status, headers)
                return "not found"
            else:
                file_data = file.read()
                file.close()
                
                status = "200 OK"
                headers = []
                start_response(status, headers)
                return file_data.decode('utf-8')

        for url, handler in self.urls:
            # ("/ctime", "show_ctime")
            if path == url:
                return handler(env, start_response)

        # 代表未找到路由信息，404错误
        status = "404 Not Found"
        headers = []
        start_response(status, headers)
        return "not found"
                     
# 逻辑编译                     
def show_ctime(env, start_response):
    status = "200 OK"
    headers = [
        ("Content-Type", "text/plain")
    ]
    start_response(status, headers)
    return time.ctime()

def say_hello(env, start_response):
    status = "200 OK"
    headers = [
        ("Content-Type", "text/plain")
    ]
    start_response(status, headers)
    return "hello itcast"


# 路由设置
urls = [
    ("/", show_ctime),
    ("/ctime", show_ctime),
    ("/sayhello", say_hello)
]
app = Application(urls)
